﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.IO;
using System.Linq;

namespace D.UtilConfiguration
{
    /// <summary>
    /// 配置文件操作
    /// </summary>
    public static class AppsettingsUtils
    {
        public static IConfiguration Configuration { get; internal set; }

        /// <summary>
        /// 获取配置实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Get<T>()
        {
            if (Configuration == null)
                return default(T);
            // Microsoft.Extensions.Configuration.Binder
            return Configuration.Get<T>();
        }

        /// <summary>
        /// 多个节点,通过.GetSection("key")["key1"]获取
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static IConfigurationSection Get(string key)
        {
            if (Configuration == null)
                return default;
            return Configuration?.GetSection(key);
        }

        /// <summary>
        /// 排除运行时 Json 后缀
        /// </summary>
        private static readonly string[] runtimeJsonSuffixs = new[]
        {
            "deps.json",
            "runtimeconfig.dev.json",
            "runtimeconfig.prod.json",
            "runtimeconfig.json"
        };


        /// <summary>
        /// 自动加载自定义 .json 配置文件
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="env"></param>
        public static void AddConfigureFiles(this IConfiguration configuration, IHostEnvironment env)
        {
            var config = new ConfigurationBuilder();

            // 获取bin目录下的配置文件
            var jsonFiles = Directory.GetFiles(AppContext.BaseDirectory, "*.json", SearchOption.TopDirectoryOnly);

            // 当前项目根目录下的配置文件
            //.Union(
            //    Directory.GetFiles(Directory.GetCurrentDirectory(), "*.json", SearchOption.TopDirectoryOnly)
            //);

            // 如果没有配置文件，中止执行
            if (!jsonFiles.Any()) return;

            // 获取环境变量名
            var envName = env.EnvironmentName;

            // 获取所有文件名
            var fileNames = jsonFiles.Select(m => Path.GetFileName(m).Split('.', StringSplitOptions.RemoveEmptyEntries))// 从文件名称分割成数组
                                     .Where(m => m.Contains(envName))// 获取包含当前环境的配置
                                     .Select(m => string.Join('.', m))// 拼接成文件名称
                                     .Distinct() // 文件名称去重
                                     .Where(m => !runtimeJsonSuffixs.Contains(m, StringComparer.OrdinalIgnoreCase)) // 文件过滤
                                     .ToList();

            //var basePath = Directory.GetCurrentDirectory();
            //var directory = Path.Join(basePath, "SqlConfig");
            //var files = Directory.GetFiles(directory, "*.config", SearchOption.AllDirectories);
            //foreach (var file in files)
            //{
            //    config.AddXmlFile(file, optional: true, reloadOnChange: true);
            //}

            // 将所有文件进行过滤
            var files = jsonFiles.Where(m => fileNames.Contains(Path.GetFileName(m))).ToList();

            // 遍历所有配置分组
            foreach (var file in files)
            {
                // 加载xml Microsoft.Extensions.Configuration.Xml
                //config.AddXmlFile(file, optional: true, reloadOnChange: true); // reloadOnChange 自动更新

                // 加载json Microsoft.Extensions.Configuration.Json
                config.AddJsonFile(file, optional: true, reloadOnChange: true); // reloadOnChange 自动更新
            }

            // 存储配置
            AppsettingsUtils.Configuration = config.Build();
        }
    }
}
